package stv5.abstracted;

import stv5.Request;
import stv5.Response;

public abstract class RequestHandler {
	
	public void handle(Connection client, Request req) {
		Response response = new Response();		
		if (handle(req, response)) {
			response.setStatus("200 OK");
			client.send(response);			
		} else handleError(client, req);
	}
	
	/**
	 * Handle the request, filling the response body
	 * 
	 * @param request
	 * @param response
	 * @return True on success, else false on error
	 */
	protected abstract boolean handle(Request request, Response response);
	
	public static void handleError(Connection client) {
		Response resp = handleError(client, null);
		client.send(resp);
	}
	
	public static Response handleError(Connection client, Request req) {
		System.out.println("Sent 404 " + ((req == null)?"":req.getRaw()));
		Response resp = new Response();
		resp.setContentType("text/html");
		resp.append(getStandardHeaders("HTTP 404 Not Found"));
		resp.append("<h1>404 File not found</h1>I could not find the page you requested.");
		resp.append(" Please go back and try again.");
		resp.append(getStandardFooters());
		resp.setStatus("404 Not Found");
		return resp;
	}		
	
	/**
	 * Generate some navigation for the bottom of the page. Always
	 *  adds a link to "Go Home" last. Send navigation in the format:
	 *  	getNavigation(TEXT1, URL1, TEXT2, URL2, ...);
	 * @param args
	 * @return
	 */
	public static String getNavigation(String... args) {
		StringBuffer buff = new StringBuffer();
		buff.append("<div>\n<ul class=\"nav\">\n");
		// make sure there are args and an even number of them
		if (args.length > 0 && (args.length & 2) > 0) {
			for (int i=0; i<args.length; i+=2) {
				buff.append("<li><a href=\""+args[i+1]+"\">"+args[i]+"</a></li>\n");
			}
		}
		buff.append("<li><a href=\"../../\">Go home</a></li>\n</ul>\n</div>");
		return buff.toString();
	}
		
	protected static String getStandardHeaders(String title) {
		StringBuffer buff = new StringBuffer();
		buff.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\""
				+" \"http://www.w3.org/TR/html4/strict.dtd\">\n");
		buff.append("<html>\n<head>\n<title>"+title+"</title>\n");
		buff.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" >\n");
		buff.append("<link rel=\"stylesheet\" href=\"files/css/default.css\" type=\"text/css\">\n");
		buff.append("</head>\n<body>\n");
		return buff.toString();
	}
	
	protected static String getStandardFooters() {
		return "\n</body>\n</html>";
	}
}
